/**
 * Description:一些注释<br/>
 * CreateTime:2019-04-12<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
package cn.cnsy123.bookwebsiteserver.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import cn.cnsy123.bookwebsiteserver.entity.SysPageItemInfo;
import cn.cnsy123.bookwebsiteserver.entity.SysRequestInfo;
import cn.cnsy123.bookwebsiteserver.service.menu.MenuInfoService;
import cn.cnsy123.bookwebsiteserver.service.sysrequest.SysRequestService;

@WebFilter(filterName = "sysPageRequestFilter",urlPatterns = {"/*"})
@Order(value = 7)
public class SysPageRequestFilter implements Filter {

    private static final String [] WEB_REQUEST_RESOURCE = {"/js","/css","/image","/img"};
    
    
    @Autowired
    private SysRequestService sysRequestService;
    
    @Autowired
    private MenuInfoService menuInfoService;
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        try {
            if(StringUtils.equalsIgnoreCase(request.getMethod(), "GET")) {
                boolean flag = true;
                for(int i = 0; i< WEB_REQUEST_RESOURCE.length; i++) {
                    if(request.getServletPath().startsWith(WEB_REQUEST_RESOURCE[i])) {
                        flag = false;
                        break;
                    }
                }
                if(flag) {
                    //获取请求页面具体信息
                    SysPageItemInfo sysPageItemInfo = menuInfoService.findPageInfoByUrl(request.getServletPath());
                    String pageName = "";
                    if(sysPageItemInfo != null) {
                        pageName = sysPageItemInfo.getPageName();
                    }
                    //记录请求页面
                    SysRequestInfo sysRequestInfo = new SysRequestInfo(pageName, request.getServletPath(), new Date(System.currentTimeMillis()));
                    sysRequestService.pushMessage(sysRequestInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        chain.doFilter(request, response);

    }

}
